package com.example.demo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;

@RestController
public class CookieSessionController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ": " + ck.getValue()));
        }

        return "获取 Cookie";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String val){
        System.out.println("bite: " + val);
        return "bite: " + val;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        // 从 cookie 获取 sessionID，再根据 sessionID 获取 Session 对象，如果没有会创建一个 session
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        session.setAttribute("age", 12);
        return "设置session成功";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        // 从 cookie 获取 sessionID，再根据 sessionID 获取 Session 对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        System.out.println("name: " + name + ", age: " + age);
        return "获取session成功";
    }

    @RequestMapping("/getSession2")
    public String gteSession2(HttpSession session){
        String name = (String) session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "name: " + name + ", age: " + age;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name, @SessionAttribute("age") Integer a){
        return "name: " + name + ", age: " + a;
    }
}
